#ifndef  __MYSQLITE_H__
#define  __MYSQLITE_H__

// #include "hv/json.hpp"
#include "hv/json.hpp"

#include <stdlib.h>

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <functional>
#include <memory>

#include <SQLiteCpp/SQLiteCpp.h>
#include <SQLiteCpp/VariadicBind.h>
#include <SQLiteCpp/Column.h>   // Column.h

using json = nlohmann::json;
using Callback = std::function<void(json&)>;
// 改为单例类；
class MySQLite
:public std::enable_shared_from_this<MySQLite>
{
   
public:
    static std::shared_ptr<MySQLite> getInstance(const std::string DbName)
    {
        if (nullptr == m_pInstance){
            atexit(destroy);
            // m_pInstance = new MySQLite( DbName );
            m_pInstance = std::make_shared<MySQLite>( DbName);
        }
        return m_pInstance;
    }
    static void destroy()
    {
        if (m_pInstance) {
            //delete m_pInstance;
            //m_pInstance = nullptr;  // SAFE_DELETE;
        }
    }

    // 复制控制语义函数删除；
    MySQLite( const MySQLite& ) = delete;
    MySQLite& operator=( const MySQLite& ) = delete;

    void queryWrapper(const std::string& tableName, std::vector <std::string>& colName, const std::string& condition, Callback cb);

    // 表名  列名  查询条件
    void query( const std::string& tableName, std::vector <std::string>& colName, const std::string& condition, Callback cb ) const;
    void insert( const std::string& tableName, std::vector <std::string>& colName, json& values  );
    void deleteValue( const std::string& tableName, const std::string& condition  );
private:
    json queryNormal(const std::string& tableName, std::vector <std::string>& colName, const std::string& condition) const;
    json queryStar( const std::string& tableName, const std::string& condition) const;
private:
    // Constructor
    MySQLite( const std::string DbName) // SQlite数据库文件名
    : m_Db(DbName, SQLite::OPEN_READWRITE|SQLite::OPEN_CREATE)   // 数据库
    {
      
        // std::cout << "DbName" << DbName << std::endl;
         // Test if the 'test' table exists
        // const bool bExists = m_Db.tableExists("COMPANY");  // 表 是否存在
        // std::cout << "SQLite table ' COMPANY' exists=" << bExists << "\n";
    }
    ~MySQLite() {}
private:
     SQLite::Database  m_Db;     // Datebase connection
     // static MySQLite* m_pInstance;
     static std::shared_ptr<MySQLite> m_pInstance;
};




#endif
